/*
 * Copyright (c) 2013, SRI International
 * All rights reserved.
 * Licensed under the The BSD 3-Clause License;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at:
 * 
 * http://opensource.org/licenses/BSD-3-Clause
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 * Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 * 
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * 
 * Neither the name of the aic-web-praise nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, 
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package com.sri.ai.lpitools.cobra.servers.xmlservers.test;

import java.util.concurrent.CountDownLatch;

import org.apache.log4j.Logger;

import com.sri.ai.lpitools.cobra.gwtutil.dataobjects.shared.LWPException;
import com.sri.ai.lpitools.cobra.server.servers.implementations.COBRAServerWrapper;

public class COBRAThread extends Thread {

	Logger logger = Logger.getLogger(COBRAThread.class);
	
	private int job;
	private COBRAServerWrapper server;
	CountDownLatch latch;
	private String result;
	private String threadID;
	public COBRAThread(COBRAServerWrapper server, CountDownLatch latch, int job, String threadID){
		this.server = server;
		this.latch = latch;
		this.job = job;
		this.setThreadID(threadID);
	}

	public String getResult(){
		return result;
	}
	
	@Override
	public void run() {
        try {
            latch.await();         
        } catch (InterruptedException e) {
            logger.error(e.getMessage(), e);
        }
        switch (job) {
	        case 1:  authenticateUser();
	                 break;
	        case 2:  deleteEvidences();
	                 break;
	        case 3:  deleteModel();
	                 break;
	        case 4:  deleteQuery();
	                 break;
	        case 5:  deleteUser();
	                 break;
	        case 6:  getEvidence();
	                 break;
	        case 7:  getModelByName();
	                 break;
	        case 8:  getQuery();
	                 break;
	        case 9:  getUsers();
	                 break;
	        case 10: listEvidences();
	                 break;
	        case 11: listModels();
	                 break;
	        case 12: listQueries();
            		 break;	                 
	        case 13: saveEvidences();
	                 break;
	        case 14: saveModel(); 
	            	break;
	        case 15: saveModelBody();
		            break;
	        case 16: saveModelInfo(); 
		            break;
	        case 17: saveQuery();
		            break;
	        case 18: saveUser();
		            break;         
	        default: authenticateUser();
	                 break;
        }		
	}
	private void saveUser() {
		try{
			boolean answer = server.saveUser("{\"user2\":\"admin\",\"admin\":true}");
			if(answer){
				result = "true";
			}
			else{
				result = "false";
			}
		} catch (LWPException e) {
			result = "false";
		}
		
	}
	private void saveQuery() {
		
		try{
			boolean answer = server.saveQuery("admin", "Is Bob Rich?", "{\"user\":\"admin\",\"queryTitle\":\"Is Ann Rich?\",\"query\":\"belief([rich(Ann)])\"}");
			if(answer){
				result = "true";
			}
			else{
				result = "false";
			}
		} catch (LWPException e) {
			result = "false";
		}
		
	}
	private void saveModelInfo() {
		try {
			boolean answer = server.saveModelBody("admin", "admin test Model 2", "{\"user\":\"admin\",\"modelTitle\":\"admin test Model 2\",\"shortDescription\":\"Model 2 for admin test\"," +
					"\"model\":\"\u0027Epidemic and Sick with Symptons Example\u0027, \u0027An example of the interplay between symptoms.\u0027, sort(People, 10, { bob, dave, rodrigo, ciaran }), randomVariable(epidemic, 0), " +
					"randomVariable(sick, 1, People, Boolean), randomVariable(fever, 1, People, Boolean), randomVariable(rash, 1, People, Boolean), randomVariable(notAtWork, 1, People, Boolean), parfactors(union({[if epidemic " +
					"then 0.001 else 0.999]}, {{(on X in People) [if epidemic then if sick(X) then 0.6 else 0.4 else if sick(X) then 0.05 else 0.95]}}, {{(on X in People) [if sick(X) then if fever(X) then 0.7 else 0.3 else if " +
					"fever(X) then 0.01 else 0.99]}}, {{(on X in People) [if sick(X) then if rash(X) then 0.6 else 0.4 else if rash(X) then 0.07 else 0.93]}}, {{(on X in People) [if sick(X) then if notAtWork(X) then 0.8 else 0.2 " +
					"else if notAtWork(X) then 0.05 else 0.95]}}, {[if notAtWork(dave) then 0.001 else 0.999]}))\"}");
			if(answer){
				result = "true";
			}
			else{
				result = "false";
			}
		} catch (LWPException e) {
			result = "false";
		}
		
	}
	private void saveModelBody() {
		try {
			boolean answer = server.saveModelBody("admin", "admin test Model 2", "{\"user\":\"admin\",\"modelTitle\":\"admin test Model 2\",\"shortDescription\":\"Model 2 for admin test\"," +
					"\"model\":\"\u0027Epidemic and Sick with Symptons Example\u0027, \u0027An example of the interplay between symptoms.\u0027, sort(People, 10, { bob, dave, rodrigo, ciaran }), randomVariable(epidemic, 0), " +
					"randomVariable(sick, 1, People, Boolean), randomVariable(fever, 1, People, Boolean), randomVariable(rash, 1, People, Boolean), randomVariable(notAtWork, 1, People, Boolean), parfactors(union({[if epidemic " +
					"then 0.001 else 0.999]}, {{(on X in People) [if epidemic then if sick(X) then 0.6 else 0.4 else if sick(X) then 0.05 else 0.95]}}, {{(on X in People) [if sick(X) then if fever(X) then 0.7 else 0.3 else if " +
					"fever(X) then 0.01 else 0.99]}}, {{(on X in People) [if sick(X) then if rash(X) then 0.6 else 0.4 else if rash(X) then 0.07 else 0.93]}}, {{(on X in People) [if sick(X) then if notAtWork(X) then 0.8 else 0.2 " +
					"else if notAtWork(X) then 0.05 else 0.95]}}, {[if notAtWork(dave) then 0.001 else 0.999]}))\"}");
			if(answer){
				result = "true";
			}
			else{
				result = "false";
			}
		} catch (LWPException e) {
			result = "false";
		}
		
	}
	private void saveModel() {
		try {
			boolean answer = server.saveModel("admin", "admin test Model 2", "{\"user\":\"admin\",\"modelTitle\":\"admin test Model 2\",\"shortDescription\":\"Model 2 for admin test\"," +
					"\"model\":\"\u0027Epidemic and Sick with Symptons Example\u0027, \u0027An example of the interplay between symptoms.\u0027, sort(People, 10, { bob, dave, rodrigo, ciaran }), randomVariable(epidemic, 0), " +
					"randomVariable(sick, 1, People, Boolean), randomVariable(fever, 1, People, Boolean), randomVariable(rash, 1, People, Boolean), randomVariable(notAtWork, 1, People, Boolean), parfactors(union({[if epidemic " +
					"then 0.001 else 0.999]}, {{(on X in People) [if epidemic then if sick(X) then 0.6 else 0.4 else if sick(X) then 0.05 else 0.95]}}, {{(on X in People) [if sick(X) then if fever(X) then 0.7 else 0.3 else if " +
					"fever(X) then 0.01 else 0.99]}}, {{(on X in People) [if sick(X) then if rash(X) then 0.6 else 0.4 else if rash(X) then 0.07 else 0.93]}}, {{(on X in People) [if sick(X) then if notAtWork(X) then 0.8 else 0.2 " +
					"else if notAtWork(X) then 0.05 else 0.95]}}, {[if notAtWork(dave) then 0.001 else 0.999]}))\"}");
					
			if(answer){
				result = "true";
			}
			else{
				result = "false";
			}
		} catch (LWPException e) {
			result = "false";
		}
		
	}
	private void saveEvidences() {
		try {
			boolean answer = server.saveEvidences("admin", "E1", "{\"user\":\"admin\",\"evidenceTitle\":\"E1\",\"evidence\":\"parfactors({[if rich(bob) then 1 else 0]})\"}");
			if(answer){
				result = "true";
			}
			else{
				result = "false";
			}
		} catch (LWPException e) {
			result = "false";
		}
		
	}
	private void listQueries() {
		try {
			result = server.listQueries("admin");
		} catch (LWPException e) {
			result = "false";
		}
		
	}
	private void listModels() {
		try {
			result = server.listModels("admin");
		} catch (LWPException e) {
			result = "false";
		}
		
	}
	private void listEvidences() {
		try {
			result = server.listEvidences("admin");
		} catch (LWPException e) {
			result = "false";
		}
		
	}
	private void getUsers() {
		try {
			result = server.getUsers();
		} catch (LWPException e) {
			result = "false";
		}
		
	}
	private void getQuery() {
		try {
			result = server.getQuery("admin", "Is Sick?");
		} catch (LWPException e) {
			result = "false";
		}
		
	}
	private void getModelByName() {
		try {
			result = server.getModelByName("admin", "admin test Model 1");
		} catch (LWPException e) {
			result = "false";
		}
		
	}
 	private void getEvidence() {
		try {
			result = server.getEvidence("admin", "E1");
		} catch (LWPException e) {
			e.printStackTrace();
			result = "false";
		}
		
	}
	private void deleteUser() {
		
		try {
		
			
			boolean answer = server.deleteUser("admin2");
			if(answer){
				result = "true";
			}
			else{
				result = "false";
			}
		} catch (LWPException e) {
			result = "false";
		}
		
		
	}
	private void deleteQuery() {
		try {
			boolean answer = server.deleteQuery("admin", "Is Ann Rich?");
			if(answer){
				result = "true";
			}
			else{
				result = "false";
			}
		} catch (LWPException e) {
			result = "false";
		}
		
		
	}
	private void deleteModel() {
		try {
			boolean answer = server.deleteModel("admin", "admin test Model 1");
			if(answer){
				result = "true";
			}
			else{
				result = "false";
			}
		} catch (LWPException e) {
			result = "false";
		}
		
		
	}
	private void deleteEvidences() {
		try {
			boolean answer = server.deleteEvidences("admin", "E1");
			if(answer){
				result = "true";
			}
			else{
				result = "false";
			}
		} catch (LWPException e) {
			logger.error(e.getMessage(), e);
		}
		
		
	}
	private void authenticateUser() {

		//String answer = "{\"user\":\"admin\",\"admin\":true}";
		
		try {
			result = server.authenticateUser("admin");
		} catch (LWPException e) {
		}
	}

	/**
	 * @return the threadID
	 */
	public String getThreadID() {
		return threadID;
	}

	/**
	 * @param threadID the threadID to set
	 */
	public void setThreadID(String threadID) {
		this.threadID = threadID;
	}

}
